package cn.hd01.sms.web;

import java.util.Random;

import cn.hd01.repository.entity.User;
import cn.hd01.service.UserService;
import cn.hd01.weixin.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.sms.SmsService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebHelper;

@Controller
@RequestMapping("/sms")
@Auth(AuthType.OFF)
public class SmsController {

	@Autowired
	private SmsService serivce;

	@Autowired
	private UserService userService;

	@RequestMapping(path = "/code", method = RequestMethod.GET)
	@ResponseBody
	public Result send(String mobile) {
		User user = userService.findByMobile(mobile);
		if (user != null){
			return new Result(0, "该手机号已经注册");
		}

		String code = code();
		serivce.send(mobile, code);
		WebHelper.session().setAttribute("code", code);
		return new Result(1, "发送验证码成功");
	}

	public String code() {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			sb.append(Math.abs(random.nextInt()) % 10);
		}
		return sb.toString();
	}
}
